#pragma once
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstring>
#include <functional>

#include "log.hpp"

namespace My_Thread
{
    static size_t __ID = 0;

    class Thread
    {
        using thread_func = std::function<void(void)>;
        static void *Routine(void *args) // 属于类内的成员函数，默认包含this指针！
        {
            Thread *self = static_cast<Thread *>(args);
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func(); // 回调处理
            return nullptr;
        }

    public:
        Thread(thread_func func)
            : _tid(0),
              _name("thread id: " + std::to_string(__ID++)),
              _detach(false),
              _run(false),
              _join(nullptr),
              _func(func)
        {
        }
        Thread(const Thread &cpy) = delete;
        Thread operator=(const Thread &cpy) = delete;
        ~Thread() = default;

        const char *GetName()
        {
            return _name.c_str();
        }

        pthread_t GetID()
        {
            return _tid;
        }

        bool IsRun()
        {
            return _run;
        }

        bool IsDecach()
        {
            return _detach;
        }
        bool Runing()
        {
            if (_run == false)
            {
                int pret = pthread_create(&_tid, NULL, Routine, this);
                //Local_Log::LOG(Local_Log::LogLever::LINFO) << "pthread_create";
                if (pret != 0)
                {
                    return false;
                }
                _run = true;
                if (_detach == true)
                {
                    pthread_detach(_tid);
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        void Stop()
        {
            if (_run == true)
            {
                pthread_cancel(_tid);
                _run = false;
                _detach = false;
            }
        }

        void Detach()
        {
            if (_detach == false)
            {
                if (_run == true)
                {
                    pthread_detach(_tid);
                }
                _detach = true;
            }
        }

        void *Join()
        {
            if (_run == true && _detach == false)
            {
                // Local_Log::LOG(Local_Log::LogLever::LINFO) << "Join";
                pthread_join(_tid, &_join);
                _run = false;
                return _join;
            }
            else
            {
                // Local_Log::LOG(Local_Log::LogLever::LINFO) << "nullptr";
                return nullptr;
            }
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _detach;
        bool _run;
        void *_join = nullptr;
        thread_func _func;
    };
}